using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Linq;

var builder = WebApplication.CreateBuilder(args);

// 添加服务到容器
builder.Services.AddControllers();
var app = builder.Build();

// 配置HTTP请求管道
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

// 添加首页端点，显示用户浏览器信息和服务器信息
app.MapGet("/", (HttpContext context) =>
{
    // 获取用户IP地址，只获取IPv4地址
    string userIP = "Unknown";
    if (context.Connection.RemoteIpAddress != null)
    {
        if (context.Connection.RemoteIpAddress.AddressFamily == AddressFamily.InterNetwork)
        {
            // IPv4地址
            userIP = context.Connection.RemoteIpAddress.ToString();
        }
        else if (context.Connection.RemoteIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
        {
            // IPv6地址，尝试转换为IPv4
            if (context.Connection.RemoteIpAddress.IsIPv4MappedToIPv6)
            {
                userIP = context.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
        }
    }
    if (userIP == "::1") userIP = "127.0.0.1";
    
    // 获取用户浏览器信息
    string userAgent = context.Request.Headers["User-Agent"].ToString() ?? "Unknown";
    
    // 解析浏览器名称和版本
    string browserInfo = ParseBrowserInfo(userAgent);
    
    var html = $@"
<!DOCTYPE html>
<html lang=""zh"">
<head>
    <meta charset=""UTF-8"">
    <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
    <title>Web Server Probe</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }}
        .header {{
            background-color: #4CAF50;
            color: white;
            padding: 20px;
            text-align: center;
        }}
        .section {{
            padding: 20px;
            border-bottom: 1px solid #eee;
        }}
        .section:last-child {{
            border-bottom: none;
        }}
        .section-title {{
            color: #333;
            margin-top: 0;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #4CAF50;
        }}
        .info-item {{
            margin-bottom: 10px;
        }}
        .info-label {{
            font-weight: bold;
            color: #555;
        }}
        .info-value {{
            color: #333;
        }}
        @media (max-width: 600px) {{
            body {{
                padding: 10px;
            }}
            .container {{
                border-radius: 0;
            }}
            .section {{
                padding: 15px;
            }}
        }}
    </style>
</head>
<body>
    <div class=""container"">
        <div class=""header"">
            <h1>Web Server Probe</h1>
        </div>
        
        <!-- 第一部分：用户浏览器信息和IP -->
        <div class=""section"">
            <h2 class=""section-title"">访客信息</h2>
            <div class=""info-item"">
                <span class=""info-label"">浏览器:</span>
                <span class=""info-value"">{browserInfo}</span>
            </div>
            <div class=""info-item"">
                <span class=""info-label"">来访IP:</span>
                <span class=""info-value"">{userIP}</span>
            </div>
        </div>
        
        <!-- 第二部分：服务器信息 -->
        <div class=""section"">
            <h2 class=""section-title"">服务器信息</h2>
            <div class=""info-item"">
                <span class=""info-label"">操作系统:</span>
                <span class=""info-value"">{Environment.OSVersion.VersionString}</span>
            </div>
            <div class=""info-item"">
                <span class=""info-label"">程序目录:</span>
                <span class=""info-value"">{Environment.CurrentDirectory}</span>
            </div>
            <div class=""info-item"">
                <span class=""info-label"">CPU架构:</span>
                <span class=""info-value"">{(Environment.Is64BitOperatingSystem ? "X64" : "X86")}</span>
            </div>
            <div class=""info-item"">
                <span class=""info-label"">处理器核心数:</span>
                <span class=""info-value"">{Environment.ProcessorCount}</span>
            </div>
            <div class=""info-item"">
                <span class=""info-label"">主机名:</span>
                <span class=""info-value"">{Environment.MachineName}</span>
            </div>
        </div>
    </div>
</body>
</html>";
    return Results.Content(html, "text/html");
})
.WithName("GetHome");

// 解析浏览器信息
string ParseBrowserInfo(string userAgent)
{
    if (string.IsNullOrEmpty(userAgent))
        return "Unknown";
        
    if (userAgent.Contains("Edg"))
        return "Microsoft Edge";
    if (userAgent.Contains("Chrome") && !userAgent.Contains("Chromium"))
        return "Google Chrome";
    if (userAgent.Contains("Firefox"))
        return "Mozilla Firefox";
    if (userAgent.Contains("Safari") && !userAgent.Contains("Chrome"))
        return "Safari";
    if (userAgent.Contains("Opera") || userAgent.Contains("OPR/"))
        return "Opera";
    if (userAgent.Contains("MSIE") || userAgent.Contains("Trident"))
        return "Internet Explorer";
        
    return "Unknown Browser";
}

app.MapGet("/api/server-info", () =>
{
    var serverInfo = new
    {
        MachineName = Environment.MachineName,
        OSVersion = Environment.OSVersion.VersionString,
        ProcessorCount = Environment.ProcessorCount,
        WorkingSet = Environment.WorkingSet,
        DotNetVersion = RuntimeInformation.FrameworkDescription,
        HostName = Dns.GetHostName()
    };
    
    return Results.Ok(serverInfo);
})
.WithName("GetServerInfo");

app.MapGet("/api/ip-info", () =>
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    var ipList = host.AddressList
        .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)
        .Select(ip => ip.ToString())
        .ToArray();
        
    var ipInfo = new
    {
        HostName = host.HostName,
        IPAddresses = ipList
    };
    
    return Results.Ok(ipInfo);
})
.WithName("GetIPInfo");

app.Run();